package com.yangit.temp.util.pdf.controller;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.yangit.temp.common.util.type.MapObjectUtils;
import com.yangit.temp.util.pdf.entity.StatementDetails;
import com.yangit.temp.util.pdf.entity.StatementShow;

/**
 * itext-PdfStamper pdfStamper（俗称抠模板）
 * 
 * @author Administrator
 *
 */
@RequestMapping("/PDFtemp")
@Controller
public class PdfTempController {

	@RequestMapping("/img")
	public void getImage(String openid, String busNum, String busDate, HttpServletRequest request,
			HttpServletResponse response) {
		FileInputStream fins = null;
		response.setContentType("image/gif");
		try {
			// 设置响应头，控制浏览器下载该文件
			// response.setHeader("content-disposition", "inline;filename=" +
			// URLEncoder.encode("投保单详情.jpg", "UTF-8"));

			String inputFileName = "E:\\豫州行结算单模板.pdf";
			String outputFile = "E:\\firstdoc.pdf";
			OutputStream os = response.getOutputStream();
			BufferedOutputStream bfos = new BufferedOutputStream(os);

			PdfStamper ps = null;
			PdfReader reader = null;

			// 2 读入pdf表单
			reader = new PdfReader(inputFileName);
			// 3 根据表单生成一个新的pdf
			ps = new PdfStamper(reader, os);
			ps.setFormFlattening(true);
			// 4 获取pdf表单
			AcroFields form = ps.getAcroFields();

			Map<String, Object> mapInfo = new HashMap<String, Object>();
			mapInfo.put("busNum", busNum);
			mapInfo.put("busDate", busDate);
			init(mapInfo);
			System.out.println(mapInfo.toString());
			Iterator iter = mapInfo.entrySet().iterator();
			while (iter.hasNext()) {
				Entry entry = (Entry) iter.next();

				String key = (String) entry.getKey();
				if (key.equals("details")) {
					List list = (List) entry.getValue();
					for (int i = 0; i < list.size(); i++) {
						StatementDetails map_details = (StatementDetails) list.get(i);
						form.setField("targetName" + 1, map_details.getTargetName());
						form.setField("price" + 1, map_details.getPrice());
						form.setField("halfPrice" + 1, map_details.getHalfprice());
						form.setField("allPrice" + 1, map_details.getHalfprice());
						form.setField("people" + 1, map_details.getPeople());
						form.setField("totalMoeny" + 1, map_details.getTotalmoeny());

					}
				} else {
					String val = (String) entry.getValue();
					System.out.println(key + ":" + val);
					form.setField(key, val);
				}

			}
			ByteArrayOutputStream out = new ByteArrayOutputStream();

			PDDocument doc = PDDocument.load(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
					outputFile);
			PDFRenderer renderer = new PDFRenderer(doc);
			int indexOfStart=1;
			int indexOfEnd = -1;
			String type ="jpg";
			int pageCount = doc.getNumberOfPages();
            for (int i = indexOfStart; i < indexOfEnd; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                //ImageIO.write(image, type, new File(fileAddress+"\\"+filename+"_"+(i+1)+"."+type));
                ImageIO.write(image, type,os) ;
            }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
	}

	@RequestMapping("/see")
	public void seepdf(HttpServletRequest request, HttpServletResponse response, ModelMap map)
			throws UnsupportedEncodingException {
		// 设置响应头，控制浏览器下载该文件
		response.setHeader("content-disposition", "inline;filename=" + URLEncoder.encode("投保单详情.pdf", "UTF-8"));

		String inputFileName = "E:\\豫州行结算单模板.pdf";
		OutputStream os = null;
		PdfStamper ps = null;
		PdfReader reader = null;

		try {
			// 1 创建一个新的文件输出流
			os = response.getOutputStream();
			;
			// 2 读入pdf表单
			reader = new PdfReader(inputFileName);
			// 3 根据表单生成一个新的pdf
			ps = new PdfStamper(reader, os);
			ps.setFormFlattening(true);
			// 4 获取pdf表单
			AcroFields form = ps.getAcroFields();

			Map<String, Object> mapInfo = new HashMap<String, Object>();
			init(mapInfo);
			System.out.println(mapInfo.toString());
			Iterator iter = mapInfo.entrySet().iterator();
			while (iter.hasNext()) {
				Entry entry = (Entry) iter.next();
				String key = (String) entry.getKey();
				String val = (String) entry.getValue();
				System.out.println(key + ":" + val);
				form.setField(key, val);
			}
			form.setField("stationName", "中民共和国");
			System.out.println(form.getField("stationName"));

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (null != ps)
					ps.close();
				if (null != reader)
					reader.close();
			} catch (DocumentException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

	@RequestMapping("/get")
	public void getpdf(HttpServletRequest request, HttpServletResponse response, ModelMap map)
			throws UnsupportedEncodingException {
		// 设置响应头，控制浏览器下载该文件
		response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("结算单详情.pdf", "UTF-8"));

		String inputFileName = "E:\\豫州行结算单模板.pdf";
		String outputFileName = "E:\\test_copy.pdf";
		OutputStream os = null;
		PdfStamper ps = null;
		PdfReader reader = null;

		try {
			// 1 创建一个新的文件输出流
			os = response.getOutputStream();
			;
			// 2 读入pdf表单
			reader = new PdfReader(inputFileName);
			// 3 根据表单生成一个新的pdf
			ps = new PdfStamper(reader, os);
			ps.setFormFlattening(true);
			// 4 获取pdf表单
			AcroFields form = ps.getAcroFields();

			Map<String, Object> mapInfo = new HashMap<String, Object>();
			init(mapInfo);
			System.out.println(mapInfo.toString());
			Iterator iter = mapInfo.entrySet().iterator();
			while (iter.hasNext()) {
				Entry entry = (Entry) iter.next();
				String key = (String) entry.getKey();
				String val = (String) entry.getValue();
				System.out.println(key + ":" + val);
				form.setField(key, val);
			}
			form.setField("stationName", "中民共和国");
			System.out.println(form.getField("stationName"));

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (null != ps)
					ps.close();
				if (null != reader)
					reader.close();
			} catch (DocumentException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

	private static void init(Map<String, Object> map) {

		StatementShow statementShow = new StatementShow();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String date = sdf.format(new Date());
		;
		statementShow.setBusDate(date);
		statementShow.setStartTime(date);
		statementShow.setStationName("郑州北站");
		statementShow.setBusNum("JZ002");
		statementShow.setCheckSeats("12");
		statementShow.setScode("sc202010270910");
		statementShow.setPlateNum("豫A5322");
		statementShow.setCompanyName("客运一公司");
		statementShow.setIsFlow("流水班");
		statementShow.setFlag("内结");
		statementShow.setTargetName("晋城站");
		try {
			MapObjectUtils s = new MapObjectUtils();
			map.putAll(s.Obj2Map(statementShow));
			map.put("lineName", statementShow.getStationName() + "----" + statementShow.getTargetName());
			System.out.println("map0:" + map.toString());
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

}